// pages/road/road.js
// 地图选点
const chooseLocation = requirePlugin('chooseLocation');
// 长按识别
var plugin = requirePlugin("WechatSI")
let manager = plugin.getRecordRecognitionManager()
const {
  request
} = require('../../utils/request')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    address: '',
    recordState: false,
    yuyinData: '',
    imgs: [],
    yuyinDataLength: 0,
    ischanged: false,
    dy: false,
    latitude: 0,
    longitude: 0,
    items: [{
        value: '畅通',
        name: '畅通',
        checked: 'true'
      },
      {
        value: '拥堵',
        name: '拥堵'
      },
      {
        value: '事故',
        name: '事故'
      },
      {
        value: '施工',
        name: '施工'
      },
      {
        value: '管制',
        name: '管制'
      }
    ]
  },
  // 获取storage
  getStorage(arr) {
    let result = {}
    arr.forEach(item => {
      let a = wx.getStorageSync(item)
      result[item] = a
    })
    return result
  },
  // 提交
  sendData(e) {
    let location = this.data.address
    let desc = this.data.yuyinData
    if (!location || this.desc) {
      wx.showToast({
        title: '请补全信息后提交',
        icon: 'none',
        duration: 2000
      })
      return
    }
    let keys = ['openid', 'avatar', 'nickname']
    let storages = this.getStorage(keys)
    let {
      openid,
      avatar,
      nickname
    } = storages
    let checked = this.data.items.filter(item => {
      return item.checked
    })
    let type = checked[0].value
    let {
      latitude,
      longitude
    } = this.data
    let imgs
    let data = {
      openid,
      avatar,
      nickname,
      type,
      location,
      desc,
      latitude,
      longitude
    }
    if (this.data.imgs) {
      data.imgs = this.data.imgs.join()
    }
    console.log(data)
    request({
        url: '/friends/create.php',
        method: 'post',
        data
      })
      .then(res => {
        console.log(res)
        if (res.data.state === 201) {
          wx.showToast({
            title: '发送成功',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '发送失败',
            icon: 'none',
            duration: 2000
          })
          // 发送成返回上一页
          wx.navigateBack({
            delta: 1,
          })
        }
      })
      .catch(err => {
        console.log(err)
      })
  },
  // 订阅
  isdy() {
    this.setData({
      dy: !this.data.dy
    })
  },

  // 绑定地图数据
  addressData(e) {
    let address = e.detail.value
    this.setData({
      address
    })
  },

  // 选择路况
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    const items = this.data.items
    for (let i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].value === e.detail.value
    }
    this.setData({
      items
    })
  },
  // 绑定语音识别框
  setDesc(e) {
    let yuyinData = e.detail.value
    // console.log(yuyinData)
    this.setData({
      yuyinData
    })
  },
  // 语音识别
  touchStart() {
    let _this = this
    manager.onRecognize = function (res) {
      console.log("current result", res.result)
    }
    manager.onStop = function (res) {
      console.log("record file path", res.tempFilePath)
      console.log("result", res.result)
      if (res.result) {
        res.result = res.result.length > 500 ? res.result.substr(0, 500) : res.result
        _this.setData({
          yuyinData: res.result
        })
      }
    }
    manager.onStart = function (res) {
      _this.setData({
        recordState: true
      })
      console.log("成功开始录音识别", res)
    }
    manager.onError = function (res) {
      console.error("error msg", res.msg)
    }
    manager.start({
      duration: 30000,
      lang: "zh_CN"
    })
  },
  touchEnd() {
    manager.stop()
    this.setData({
      recordState: false
    })
  },

  // 上传照片
  setImgs() {
    let _this = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: 'http://kg.zhaodashen.cn/v2/upload.php',
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'file': tempFilePaths[0]
          },
          success(res) {
            let data = JSON.parse(res.data)
            let {
              url,
              img
            } = data.data
            let imgUrl = `${url}/${img}`
            console.log(imgUrl)
            imgUrl = imgUrl.split()
            _this.setData({
              imgs: [...imgUrl, ..._this.data.imgs]
            })
          }
        })
      }
    })
  },

  // 获取定位信息
  getAddress() {
    let {
      latitude,
      longitude
    } = this.getStorage(['latitude', 'longitude'])
    let key = 'LPABZ-EUYL6-XBYSI-E7BUD-TGVDS-4RFQO'; //使用在腾讯位置服务申请的key
    let referer = '堵车查询'; //调用插件的app的名称

    const location = JSON.stringify({
      latitude: latitude,
      longitude: longitude
    });
    const category = '生活服务,娱乐休闲';
    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`
    });
  },
  // 获取定位函数
  getLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        const latitude = res.latitude
        const longitude = res.longitude
        wx.setStorageSync('latitude', latitude)
        wx.setStorageSync('longitude', longitude)
        this.setData({
          latitude,
          longitude
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getLocation()
    const location = chooseLocation.getLocation();
    console.log(location)
    if (location) {
      let address = location.address
      let {
        latitude,
        longitude
      } = location
      console.log(address)
      this.setData({
        latitude,
        longitude,
        address
      })
    }

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    chooseLocation.setLocation(null);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})